import { Injectable, UnauthorizedException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Submission } from './submission.entity';
import { CreateSubmissionDto } from './dto/create-submission.dto';
import { Project } from '../project/project.entity';
import { User } from '../user/user.entity';
import { ProjectShare } from '../project/project-share.entity';
import { UserService } from '../user/user.service';

@Injectable()
export class SubmissionService {
  constructor(
    @InjectRepository(Submission)
    private readonly submissionRepository: Repository<Submission>,
    @InjectRepository(ProjectShare)
    private readonly projectShareRepository: Repository<ProjectShare>,
    private readonly userService: UserService,
  ) {}

  async create(createSubmissionDto: CreateSubmissionDto, project: Project): Promise<Submission> {
    const submission = new Submission();
    submission.data = createSubmissionDto.data;
    submission.project = project;
    return this.submissionRepository.save(submission);
  }

  async createFromShare(createSubmissionDto: CreateSubmissionDto, shareToken: string): Promise<Submission> {
    // 根据分享令牌查找项目分享记录
    const projectShare = await this.projectShareRepository.findOne({
      where: { shareToken, isActive: true },
      relations: ['project', 'sharedBy']
    });

    if (!projectShare) {
      throw new Error('Invalid or inactive share token');
    }

    const submission = new Submission();
    submission.data = createSubmissionDto.data;
    submission.project = projectShare.project;
    submission.recommendedBy = projectShare.sharedBy; // 设置推荐管理员
    submission.projectShare = projectShare; // 关联项目分享记录
    
    return this.submissionRepository.save(submission);
  }

  async findAllByProject(projectId: number): Promise<Submission[]> {
    return this.submissionRepository.find({
      where: { project: { id: projectId } },
      relations: ['project', 'project.owner', 'recommendedBy'],
    });
  }

  async findAll(): Promise<Submission[]> {
    return this.submissionRepository.find({ 
      relations: ['project', 'project.owner', 'recommendedBy'],
      order: { submittedAt: 'DESC' }
    });
  }

  async findAllForUser(user: User): Promise<Submission[]> {
    if (user.level === 1) { // Top-level manager sees everything
      return this.findAll();
    }

    // Get subordinates
    const subordinates = await this.userService.getSubordinates(user.id);
    const subordinateIds = subordinates.map(s => s.id);
    
    // Get superiors
    const superiors = await this.userService.getSuperiors(user.id);
    const superiorIds = superiors.map(s => s.id);
    
    // Combine user, subordinates, and superiors
    const allUserIds = [user.id, ...subordinateIds, ...superiorIds];

    if (allUserIds.length === 0) {
        return [];
    }

    return this.submissionRepository.createQueryBuilder('submission')
      .leftJoinAndSelect('submission.project', 'project')
      .leftJoinAndSelect('project.owner', 'owner')
      .leftJoinAndSelect('submission.recommendedBy', 'recommendedBy')
      .where('owner.id IN (:...ids)', { ids: allUserIds })
      .orderBy('submission.submittedAt', 'DESC')
      .getMany();
  }

  async findByRecommendedBy(recommendedById: number, user: User): Promise<Submission[]> {
    const queryBuilder = this.submissionRepository.createQueryBuilder('submission')
      .leftJoinAndSelect('submission.project', 'project')
      .leftJoinAndSelect('project.owner', 'owner')
      .leftJoinAndSelect('submission.recommendedBy', 'recommendedBy')
      .where('submission.recommendedBy.id = :recommendedById', { recommendedById })
      .orderBy('submission.submittedAt', 'DESC');

    // 根据用户级别限制查看权限
    if (user.level !== 1) {
      // 获取用户可以查看的项目所有者ID
      const subordinates = await this.userService.getSubordinates(user.id);
      const subordinateIds = subordinates.map(s => s.id);
      const superiors = await this.userService.getSuperiors(user.id);
      const superiorIds = superiors.map(s => s.id);
      const allUserIds = [user.id, ...subordinateIds, ...superiorIds];
      
      if (allUserIds.length > 0) {
        queryBuilder.andWhere('owner.id IN (:...ids)', { ids: allUserIds });
      } else {
        return [];
      }
    }

    return queryBuilder.getMany();
  }

  async findByProjectAndRecommendedBy(projectId: number, recommendedById: number, user: User): Promise<Submission[]> {
    const queryBuilder = this.submissionRepository.createQueryBuilder('submission')
      .leftJoinAndSelect('submission.project', 'project')
      .leftJoinAndSelect('project.owner', 'owner')
      .leftJoinAndSelect('submission.recommendedBy', 'recommendedBy')
      .where('submission.project.id = :projectId', { projectId })
      .andWhere('submission.recommendedBy.id = :recommendedById', { recommendedById })
      .orderBy('submission.submittedAt', 'DESC');

    // 根据用户级别限制查看权限
    if (user.level !== 1) {
      const subordinates = await this.userService.getSubordinates(user.id);
      const subordinateIds = subordinates.map(s => s.id);
      const superiors = await this.userService.getSuperiors(user.id);
      const superiorIds = superiors.map(s => s.id);
      const allUserIds = [user.id, ...subordinateIds, ...superiorIds];
      
      if (allUserIds.length > 0) {
        queryBuilder.andWhere('owner.id IN (:...ids)', { ids: allUserIds });
      } else {
        return [];
      }
    }

    return queryBuilder.getMany();
  }
}